<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { ElButton, ElTag, ElMessageBox } from 'element-plus'

import { Table } from '@/components/Table'
import {
  sysCrontabListApi,
  sysCrontabEditApi,
  sysCrontabAddApi,
  sysCrontabDelApi
  // ucAppBatchDelApi
} from '@/api/sys/crontab'
import { useTable } from '@/hooks/web/useTableTest'
import { h, ref, unref, reactive } from 'vue'
import Edit from './components/Edit.vue'
import See from './components/See.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useIcon } from '@/hooks/web/useIcon'
// 获取字典
import { useCache } from '@/hooks/web/useCache'
const { wsCache } = useCache()
const dict: any = wsCache.get('dict')
// 字典通过value获取label
const getDictLabel = (type, value) => {
  let data = dict[type].find((item) => {
    return item.value == value
  })
  return data ? data.label : ''
}

const iconEdit = useIcon({ icon: 'ep:edit' })
const iconSee = useIcon({ icon: 'ep:view' })
const iconDel = useIcon({ icon: 'ep:delete' })
const { register, tableObject, methods } = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: sysCrontabListApi,
  response: {
    data: 'data',
    count: 'count'
  }
})

const { getList, setSearchParams } = methods

getList()

const { t } = useI18n()

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'id',
    label: '主键',
    width: 60,
    fixed: 'left',
    table: { show: true },
    search: { show: false },
    form: { show: false },
    detail: { show: false }
  },
  {
    field: 'name',
    label: '任务名称',
    width: 120,
    table: { show: true },
    search: { show: true },
    form: { show: true },
    detail: { show: true }
  },
  {
    field: 'type',
    label: '任务类型',
    width: 120,
    table: { show: true },
    search: { show: true },
    // form: { show: true },
    form: { show: true, component: 'Select', componentProps: { options: dict.crontab_type } },
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('crontab_type', cellValue)
    },
    detail: { show: true }
  },
  {
    field: 'api_code',
    label: '接口代码',
    width: 120,
    table: { show: true },
    search: { show: false },
    form: { show: true },
    detail: { show: true }
  },
  {
    field: 'is_stop',
    label: '是否停用',
    table: { show: true },
    formatter: (_: Recordable, __: TableColumn, cellValue: string) => {
      return h(
        ElTag,
        {
          type: cellValue === '0' ? 'success' : 'warning'
        },
        () => (cellValue === '0' ? t('停用') : t('启用'))
      )
    },
    search: { show: false },
    form: {
      component: 'Select',
      componentProps: {
        options: dict.is_stop
      }
    },
    detail: { show: true }
  },
  {
    field: 'time',
    label: '执行时间点',
    width: 170,
    table: { show: true },
    search: { show: false },
    form: { show: false },
    detail: { show: false }
  },
  {
    field: 'year',
    label: '年',
    componentProps: {
      placeholder: '默认*'
    },
    table: { show: false },
    search: { show: false },
    form: { show: true },
    detail: { show: true }
  },
  {
    field: 'month',
    label: '月',
    table: { show: false },
    search: { show: false },
    form: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        disabled: false,
        type: 'month',
        valueFormat: 'MM'
      }
    },
    detail: { show: true }
  },
  {
    field: 'day',
    label: '日',
    table: { show: false },
    search: { show: false },
    form: { show: true },
    detail: { show: true }
  },
  {
    field: 'hour',
    label: '时',
    table: { show: false },
    search: { show: false },
    form: { show: true },
    detail: { show: true }
  },
  {
    field: 'minute',
    label: '分',
    table: { show: false },
    search: { show: false },
    form: { show: true },
    detail: { show: true }
  },
  {
    field: 'week',
    label: '周',
    table: { show: false },
    search: { show: false },
    form: { show: true },
    detail: { show: true }
  },
  {
    field: 'plan_start_time',
    label: '开始时间',
    width: 170,
    table: { show: true },
    search: { show: false },
    form: { show: false },
    detail: { show: true }
  },
  {
    field: 'plan_end_time',
    label: '结束时间',
    width: 170,
    table: { show: true },
    search: { show: false },
    form: { show: false },
    detail: { show: true }
  },
  {
    field: 'last_execution_time',
    label: '上次执行时间',
    width: 170,
    table: { show: true },
    search: { show: false },
    form: { show: false },
    detail: { show: true }
  },
  {
    field: 'next_execution_time',
    label: '下次执行时间',
    width: 170,
    table: { show: true },
    search: { show: false },
    form: { show: false },
    detail: { show: true }
  },
  {
    field: 'create_user_name',
    label: '创建人',
    table: { show: true },
    search: { show: false },
    form: { show: false },
    detail: { show: true }
  },
  {
    field: 'create_time',
    label: '创建时间',
    width: 170,
    table: { show: true },
    search: { show: false },
    form: { show: false },
    detail: { show: true }
  },
  {
    field: 'action',
    width: 300,
    fixed: 'right',
    label: '操作',
    form: { show: false },
    detail: { show: false }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)

const dialogTitle = ref('')

const actionType = ref('')

const action = async (type: string, row: any = {}) => {
  actionType.value = type
  switch (type) {
    case 'edit':
      dialogTitle.value = '编辑'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'add':
      dialogTitle.value = '新增'
      tableObject.currentRow = {
        is_stop: '0'
      }
      dialogVisible.value = true
      break
    case 'see':
      dialogTitle.value = '查看'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'del':
      ElMessageBox.confirm('确定要删除这个定时任务吗？', '删除', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          apiDel(row.id)
        })
        .catch(() => {
          console.log('这里是取消confirm弹框')
        })
      break
    default:
      console.log('未知类型')
  }
}

const apiDel = async (id) => {
  let delRes = await sysCrontabDelApi({ id })
    .catch(() => {})
    .finally(() => {
      loading.value = false
    })
  if (delRes) {
    getList()
  }
}

const editRef = ref<ComponentRef<typeof Edit>>()

const loading = ref(false)

const save = async () => {
  const edit = unref(editRef)
  switch (actionType.value) {
    case 'edit':
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          loading.value = true
          const data = (await edit?.getFormData()) as any
          let res = await sysCrontabEditApi(data)
            .catch(() => {})
            .finally(() => {
              loading.value = false
            })
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            getList()
          }
        }
      })

      break
    case 'add':
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          loading.value = true
          const data = (await edit?.getFormData()) as any
          let res = await sysCrontabAddApi(data)
            .catch(() => {})
            .finally(() => {
              loading.value = false
            })
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            getList()
          }
        }
      })
      break
    default:
      console.log('未知类型')
  }
}
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />

    <div class="mb-10px">
      <ElButton type="primary" @click="action('add')">新增</ElButton>
      <!-- <ElButton :loading="delLoading" type="danger" @click="delData()"> 批量删除 </ElButton> -->
    </div>

    <Table
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :border="true"
      :pagination="{
        total: tableObject.count
      }"
      @register="register"
    >
      <template #time="{ row }: { row: any }">
        <span v-if="row.type == 1">{{
          (row.year ? '年:' + row.year + '   ' : '') +
          (row.month ? '月:' + row.month + '   ' : '') +
          (row.day ? '日:' + row.day + '   ' : '') +
          (row.hour ? '时:' + row.hour + '   ' : '') +
          (row.minute ? '分:' + row.minute + '   ' : '') +
          (row.week ? '周:' + row.week : '   ')
        }}</span>
      </template>
      <template #action="{ row }">
        <ElButton type="primary" :icon="iconEdit" @click="action('edit', row)" title="编辑">
          编辑
        </ElButton>
        <ElButton type="success" :icon="iconSee" @click="action('see', row)" title="详情">
          详情
        </ElButton>
        <ElButton type="danger" :icon="iconDel" @click="action('del', row)" title="删除">
          删除
        </ElButton>
      </template>
    </Table>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Edit
      v-if="actionType == 'edit' || actionType == 'add'"
      ref="editRef"
      :form-schema="allSchemas.formSchema"
      :current-row="tableObject.currentRow"
    />
    <See
      v-if="actionType == 'see'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
    />
    <template #footer>
      <ElButton v-if="actionType !== 'see'" type="primary" :loading="loading" @click="save()">
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>
</template>
